/**
 * @file 通过 API 来获取，app_back 是通过 headless browser 来获取
 */

const axios = require('axios')
const dayjs = require('dayjs')
const fs = require('fs')

// 获取我关注的 UP 主列表
axios.get('https://account.bilibili.com/api/member/getCardByMid?mid=485828245').then(async res => {
    const { attentions } = res.data.card
    const list = []
    const longVideoUps = []

    for (const mid of attentions) {
        const {data:{data:{item}}} = await axios.get(`https://app.biliapi.com/x/v2/space/archive/cursor?vmid=${mid}`)
        if (item) {
            const items = item.filter(cur => cur.duration && cur.author)
            const [firstVideo] = items
            const date = firstVideo.ctime * 1000
            const diffDay = dayjs(Date.now()).diff(date, 'd')
            const author = await (async function(){
                if (firstVideo.author.endsWith(" 等联合创作")){
                    for (const a of items) {
                        if(!a.author.endsWith(" 等联合创作")){
                            return a.author
                        }
                    }
                    console.log('另开请求获取name')
                    const res = await axios.get(`https://account.bilibili.com/api/member/getCardByMid?mid=${mid}`)
                    return res.data.card.name
                }
                return firstVideo.author
            })()
            list.push({
                name: author,
                title: firstVideo.title,
                date: dayjs(date).format("YYYY-MM-DD"),
                diff: diffDay > 0 ? `${diffDay}天前` : firstVideo.publish_time_text,
                timestamp: date
            })

            if (item.slice(0, 5).map(c => c.duration).every(c => c > 900)) {
                longVideoUps.push(author)
            }

            console.log(`『${author}』的数据已获取完成`)
        }
        
        await sleep()
    }
    
    const result = list
        .toSorted((a, b) => a.timestamp - b.timestamp)
        .reduce((prev, cur) =>
            prev + `  up：${cur.name}\n视频：${cur.title}\n时间：${cur.date}\n相差：${cur.diff}\n\n`
        , '')

    fs.writeFileSync("结果.txt", result, "utf-8");
    console.log("结果写入完成")
    
    if (longVideoUps.length) {
        fs.writeFileSync("长视频的up主们.txt",longVideoUps.join("\n"),"utf-8");
        console.log("长视频的up主们写入完成")
    }
})

function sleep() {
    return new Promise(resolve => setTimeout(resolve, 1000))
}
